<?php
/***************************************************************
*  Copyright notice
*  (c) 2009, jianyuzhu@gmail.com
*  All rights reserved
*  This script is part of the PPEMI project.
***************************************************************/

class UserSessionBase extends Base {
	var $userid = 0;
	var $username = 0;
	var $usertype = '';
	
	//constructor
	function UserSessionBase() {
		parent::Base();
	}
	
	//methods
	function checkUser($sid) {
		$sid = func_db_input($sid);
		$query = "select * from pp_sessions where sesskey = '" . $sid . "'";
		$row = $this->adb->getRow($query);
		if( strlen($row['sesskey']) > 0 && $row['expiry'] > 0 ) {
			$data = $this->_get_session_data($row['value']);
			
			if( $data['suser']->usertype == 'customer' ) {
				$this->userid = $data['suser']->userid;
				$this->username = $data['suser']->username;
				$this->usertype = $data['suser']->usertype;
				
				return true;
			}
		}
		
		return false;
	}
	
	function checkAdmin($sid) {
		$sid = func_db_input($sid);
		$query = "select * from pp_sessions where sesskey = '" . $sid . "'";
		$row = $this->adb->getRow($query);
		if( strlen($row['sesskey']) > 0 && $row['expiry'] > 0 ) {
			$data = $this->_get_session_data($row['value']);
			
			if( $data['suser']->usertype == 'admin' ) {
				$this->userid = $data['suser']->userid;
				$this->username = $data['suser']->username;
				$this->usertype = $data['suser']->usertype;
				
				return true;
			}
		}
		
		return false;
	}
	
	//private
	function _get_session_data($session_data) {
		$session_data = trim($session_data);
		$l = strlen($session_data);
		$s = 0;
		$c = 0;
		$ss = array();
		while($s < $l) {
			$si = $this->_get_session_item($session_data, $s, $l);
			
			$p = strpos($si, '|');
			$n = substr($si, 0, $p);
			$v = substr($si, $p+1);
			$ss[$n] = unserialize($v);
			
			$s += strlen($si);
			
			//
			$c++;
			if( $c > 10 ) {
				break;
			}
		}
		
		return $ss;
	}
	
	function _get_session_item($session_data, $start, $length) {
		for($i=$start; $i<$length; $i++) {
			if( $session_data[$i] == '{' ) {
				if( isset($tag) ) {
					$tag++;
				} else {
					$tag = 1;
				}
			} elseif( $session_data[$i] == '}' ) {
				$tag--;
			} elseif( isset($tag) && $tag < 1 ) {
				break;
			}
		}
		
		return substr($session_data, $start, $i-$start);
	}
}
//
?>